<script setup lang="ts">
import { ref, onMounted, toRaw, reactive, watch } from 'vue'
import { useRoute, useRouter } from "vue-router";
import { teachLiveOpenLive } from '../../stores/api/live'
import { message } from 'ant-design-vue';
import type { UnwrapRef } from 'vue';
import type { Rule } from 'ant-design-vue/es/form';
import { useCounterStore } from '../../stores/counter'
import type { UploadProps } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { upload, videoUpload } from '../../utils/upload' // 引入js
import { getVideoDuration } from '../../utils/utils';
const router:any = useRouter()
const route:any = useRoute()
const fileList = ref<UploadProps['fileList']>([])
const uploading = ref<boolean>(false);
const store = useCounterStore()

interface FormState {
    operator: string;
    url: string; // Array<string>;
    start_time: string;
    end_time: string | number;
    video_time: number
}
const formRef = ref();
const labelCol = { span: 3 };
const wrapperCol = { span: 24 };
const formState: UnwrapRef<FormState> = reactive({
    operator: '', // 备注
    url: '', // 上传附件文件 测试地址  video/console/20250811/1754897038879_jlu8ep.mp4
    start_time: '', // 开始时间
    end_time: '', //结束时间
    video_time: 0
});
const rules: Record<string, Rule[]> = {
//   title: [
//     { required: true, message: '请输入标题', trigger: 'change' },
//   ]
};
// 提交
const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      console.log('values', formState, toRaw(formState));
      console.log('添加')
      createHomework()
    })
    .catch(error => {
      console.log('error', error);
    });
};
// 取消
const resetForm = () => {
  formRef.value.resetFields();
//   emits("backUpdateChange2", { isShowUpdatePw: false});
  fileList.value = []
  router.go(-1)
};

// 调用创建公开课接口
const createHomework = () => {
    let obj = {
        "url": formState.url ? formState.url : '',
        "operator": formState.operator,
        "video_time": formState.video_time,
        "start_time": formState.start_time ? store.getTimestamp(formState.start_time) : '' // 开始时间
    }
    console.log(obj)
    teachLiveOpenLive(obj, 'post').then((res: any) => {
        console.log(res)
        if(res.code == 200) {
            message.success('创建成功');
            formRef.value.resetFields();
            fileList.value = []
            formState.url = ''
            router.go(-1)
        } else {
            message.error(res.msg);
        }
    }).catch((err: any) => {
        console.log(err)
    })
}

// 上传视频
const beforeUpload: UploadProps['beforeUpload'] = file => {
  const isPNG = file.type === 'image/png';
//   if (!isPNG) {
//     message.error(`${file.name} is not a png file`);
//   }
//   return isPNG || Upload.LIST_IGNORE;
  return true
};
// 视频上传
const handleUpload = async (data) => {
    console.log('上传11')
    console.log(data,'handleUpload')
    const duration = await getVideoDuration(data.file);
    formState.video_time = Math.round(duration)
    formState.end_time = Number(store.getTimestamp(formState.start_time)) + formState.video_time
    console.log(formState.video_time,`视频时长：${formState.video_time}秒`);
    videoUpload(data.file,res => {
      console.log(res,'ddddd')
      if(res) {
            const startIndex = res.indexOf('/') + 1;
            const urls = res.substring(startIndex);
            formState.url = urls
            fileList.value = [ data.file];
            console.log(fileList.value)
            console.log(urls)
      }
      uploading.value = false;
    })
}
// 删除
const handleRemov = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  formState.url = ''
}

const handleDate = (date, dateString: string) => {
   console.log(date, dateString)
   formState.end_time = Number(store.getTimestamp(date)) + formState.video_time
}

// const disabledDate = (current: Dayjs) => {
//     console.log(current,dayjs().endOf('day'),'current')
//   // Can not select days before today and today
//   return current && current < dayjs().endOf('day');
// };


// watch(route.query.data, (newVal:any, oldValue:any) => {
//    console.log('data',newVal, oldValue)
// //    formState.title = newVal.title
// //    formState.permission = newVal.permission
// //    formState.thumbnail = newVal.thumbnail
// //    imageUrl.value = getImgUrl(newVal.thumbnail)
// })
onMounted(() => {
});
</script>

<template>
  <div class="open-class">
    <a-card class="top-content-p" title="创建公开课" style="width: 100%">
        <div class="live-left">
            <a-form
                ref="formRef"
                :model="formState"
                :rules="rules"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-form-item name="start_time" label="直播开始时间">
                    <a-date-picker
                        v-model:value="formState['start_time']"
                        show-time
                        showNow
                        :disabled-date="store.disabledDate"
                        :disabled-time="store.disabledDateTime"
                        placeholder="请选择直播开始时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        @change="handleDate"
                    />
                </a-form-item>
                <a-form-item name="end_time" label="直播结束时间" v-if="formState.end_time">
                    <div>{{ store.timestampChangDate(Number(formState.end_time) * 1000) }}</div>
                </a-form-item>
                <a-form-item name="url" label="视频地址">
                        <a-upload
                            v-model:file-list="fileList"
                            :before-upload="beforeUpload"
                            :customRequest="handleUpload"
                            @remove="handleRemov"
                            accept=".mp4,.flv,.hls"
                        >
                            <a-button>
                            <upload-outlined></upload-outlined>
                               上传视频
                            </a-button>
                        </a-upload>
                    </a-form-item>
                <a-form-item ref="operator" label="备注" name="operator">
                    <a-textarea
                        v-model:value="formState.operator"
                        placeholder="请输入备注"
                        :auto-size="{ minRows: 4}"
                    />
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 24, offset: 4 }" style="text-align: center;">
                    <a-button class="btn-ss" type="primary" @click="onSubmit">提 交</a-button>
                    <a-button style="margin-left: 10px" @click="resetForm">取 消</a-button>
                </a-form-item>
            </a-form>
        </div>
    </a-card>
  </div>
</template>

<style scoped>
.open-class{
   display: flex;
   color: #333;
   /* background-color: rgba(22,24,35,1); */
}
.top-content-p{
    border-radius: initial;
}
.live-left{
   flex: 3;
   width: 80%;
   min-width: 230px;
   margin: auto;
   overflow: hidden;
   padding:0 15px;
}
.live-video{
  width: 100%;
  height: 100%;
  object-fit: cover; /* 确保视频撑满父容器 */
}
.basic-info{
    display: flex;
    color: #999;
}
.cover-img{
    width: 50px;
    border-radius: 8px;
}
.cover-g{
    /* background-color: rgb(51,52,63); */
    width: 130px;
    height: 132px;
    line-height: 26px;
    text-align: center;
    padding: 10px 0;
    border-radius: 10px;
}
.cover-image{
    width: 100%;
    height: 100%;
}
.cover-image img{
    width: 100%;
    height: 100%;
}
.input-item-dd{
    /* height: 30px; */
    /* padding-top: 0; */
    /* background-color: transparent; */
    font-size: 14px; /* 占位符字体大小 */
    /* border:none; */
    /* outline: none; */
    color: #000;
}
.input-item-dd::placeholder {
  font-size: 14px; /* 占位符字体大小 */
  color: #999; /* 占位符字体颜色 */
}
.type-item{
  padding-left:10px;
  margin-top: 20px;
}
.type-s{
    padding: 5px 15px;
    margin-right: 10px;
    border-radius: 10px;
    cursor: pointer;
}
.active{
    background-color: rgb(51,52,63);
}

.positin-boottom{
    position: absolute;
    bottom: 10px;
    width: 94%;
}
.bottom-item-a{
    width:100%;
   display: flex;
   justify-content: space-between;
   align-items: center;
   color: #fff;
   background-color: #080808;
   padding: 8px 15px;
   border-radius: 10px;
}
.btn-ss{
    background-color: #fe5d26;
    height: 34px;
}
.btn-ss:hover{
    background-color: #fe5d26;
}
.live-right{
    color: #fff;
   flex:1;
   position:relative;
   /* background-color: rgb(37,38,50); */
   padding-right: 15px;
}
.live-right-list{
    background-color: rgb(51,52,63);
    padding: 10px 20px;
    height: 22vh;
    border-radius: 10px;
    overflow-y: auto;
}
.live-item{
   display: flex;
   align-items: center;
   justify-content: center;
   color: #898687;
   margin-top: 10px;
}
.live-num{
    line-height: 30px;
    margin-bottom: 20px;
}
.ranking{
    margin-right: 30px;
}
.nick-name{
    margin:0 20px 0 10px;
}
.img-avatar{
    width: 35px;
    height: 35px;
    border-radius: 50%;
}
.grade{
    width: 30px;
}

.live-message{
    padding: 10px 20px;
    background-color: rgb(37,38,50);
    height: 70vh;
    overflow-y: auto;
}
.msg-item{
    display: flex;
    align-items: flex-start;
    margin-top: 8px;
}
.msg-grade{
    width: 40px;
}
.name{
 color: #8ce7ff;
 margin:0 10px;
}
.msg-content{
    line-height: 25px;
}
.bottom-contt{
    position: absolute;
    bottom: 0;
    width: 100%;
    /* background-color: rgb(37,38,50); */
}
.bottom-send{
    display: flex;
    align-items: center;
    color: #fff;
    background-color: rgb(65,66,76);
    margin: 10px 15px 10px 0;
    padding: 8px;
    border-radius: 10px;
}
.send-input{
    background-color: rgb(65,66,76);
    font-size: 16px; /* 占位符字体大小 */
    border:none;
    color: #fff;
}
.send-input::placeholder {
  font-size: 14px; /* 占位符字体大小 */
  color: #999; /* 占位符字体颜色 */
}
.read-the-docs {
  color: #888;
}
</style>